package com.txcb.lib.base.ui

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.cbtx.module.base.ui.MyOnClickListener

open abstract class BaseFragment : Fragment() {


    lateinit var mContentView: View
    var isViewPrepared = false// 标识fragment视图已经初始化完毕
    var hasFetchData = false// 标识已经触发过懒加载数据
    var mContext:Context?= null

    private var mIsCreateView = true


    fun newFragment(fragment: Fragment): Fragment {
        return newFragment(fragment, null)
    }

    fun newFragment(fragment: Fragment, bundle: Bundle?): Fragment {
        val newFragment = fragment
        if (bundle != null) {
            newFragment.arguments = bundle
        }
        return newFragment
    }


    /**
     * 设置fragment view
     * @return
     */
    abstract fun getLayoutId(): Int


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        mContentView = inflater.inflate(getLayoutId(), null)
        return mContentView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        if(mIsCreateView){
            initView(view)
            mIsCreateView = false
        }

    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        isViewPrepared = true

        lazyFetchDataIfPrepared()
    }
    override fun onDestroyView() {
        super.onDestroyView()
        isViewPrepared = false
        hasFetchData = false
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isVisibleToUser) {
            lazyFetchDataIfPrepared()
        }
    }

    private fun lazyFetchDataIfPrepared() {
        // 用户可见fragment && 没有加载过数据 && 视图已经准备完毕
        if (userVisibleHint && !hasFetchData && isViewPrepared) {
            hasFetchData = true
            lazyFetchData()
        }
    }

    /**
     * 初始化fragment view 控件
     * @param view
     */
    abstract fun initView(view: View)

    // 初始化数据
    protected open fun initData(){}

    /**
     * 懒加载数据
     */
    abstract fun lazyFetchData();

    fun addClickListener(view: View) {
        //防止暴力点击，统一处理
        view.setOnClickListener(object : MyOnClickListener() {
            override fun onMyClick(view: View) {
                onMyViewClick(view)
            }
        })
    }

    abstract fun onMyViewClick(view: View)



}